
// 切换标签页
function switchTab(tabName) {
	// 隐藏所有标签内容
	document.querySelectorAll('.tab-content').forEach(tab => {
		tab.classList.remove('active');
	});

	// 移除所有标签的活动状态
	document.querySelectorAll('.tab').forEach(tab => {
		tab.classList.remove('active');
	});

	// 显示选中的标签内容
	document.getElementById(tabName + 'Tab').classList.add('active');

	// 设置选中的标签为活动状态
	event.target.classList.add('active');
}

// 添加输出信息
function addOutput(message, type = 'info') {
	const output = document.getElementById('output');
	const line = document.createElement('div');
	line.className = `output-line output-${type}`;
	line.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
	output.appendChild(line);
	output.scrollTop = output.scrollHeight;
}

// 清空输出
function clearOutput() {
	document.getElementById('output').innerHTML = '';
	addOutput('输出已清空', 'info');
}

// 导出日志
function exportLogs() {
	const output = document.getElementById('output');
	const logs = output.innerText;
	const blob = new Blob([logs], { type: 'text/plain' });
	const url = URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.download = `lunar-astral-logs-${new Date().toISOString().slice(0, 10)}.txt`;
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
	URL.revokeObjectURL(url);
	addOutput('日志已导出', 'success');
}

// 获取表单数据
function getFormData() {
	return {
		system_url_port: parseInt(document.getElementById('system_url_port').value),
		system_dev_mode: document.getElementById('system_dev_mode').checked,
		use_local_network: document.getElementById('use_local_network').checked,
		port_release: document.getElementById('port_release').checked,
		model_system_port: parseInt(document.getElementById('model_system_port').value),
		model_url_port: parseInt(document.getElementById('model_url_port').value),
		model_file_path: document.getElementById('model_file_path').value,
		model_embedding_index: document.getElementById('model_embedding_index').value,
		model_reasoning_index: document.getElementById('model_reasoning_index').value,
		model_visualing_index: document.getElementById('model_visualing_index').value,
		out_base: document.getElementById('out_base').value,
		part_size_mb: parseInt(document.getElementById('part_size_mb').value),
		compression_level: parseInt(document.getElementById('compression_level').value),
		package_level: parseInt(document.getElementById('package_level').value),
	};
}

// 启动服务
function startService() {
	const config = getFormData();
	updateServiceStatus('starting', '服务启动中...', '正在初始化系统，请稍候...');
	addOutput('正在启动 Lunar Astral Agents 服务...', 'info');

	fetch('/control_panel/start', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
		},
		body: JSON.stringify(config)
	})
		.then(response => response.json())
		.then(data => {
			if (data.success) {
				addOutput('服务启动命令已发送', 'success');
				addOutput(`进程ID: ${data.pid}`, 'info');
				addOutput('服务正在启动，请查看控制台输出...', 'info');

				// 模拟服务启动成功
				setTimeout(() => {
					updateServiceStatus('online', '服务运行中', `服务运行在端口 ${config.system_url_port}`);
				}, 3000);
			} else {
				addOutput(`启动失败: ${data.error}`, 'error');
				updateServiceStatus('offline', '服务启动失败', data.error);
			}
		})
		.catch(error => {
			addOutput(`请求失败: ${error}`, 'error');
			updateServiceStatus('offline', '服务启动失败', error);
		});
}

// 停止服务
function stopService() {
	updateServiceStatus('starting', '服务停止中...', '正在关闭服务进程...');
	addOutput('正在停止服务...', 'info');

	fetch('/control_panel/stop', {
		method: 'POST'
	})
		.then(response => response.json())
		.then(data => {
			if (data.success) {
				addOutput('服务停止命令已发送', 'success');

				// 模拟服务停止
				setTimeout(() => {
					updateServiceStatus('offline', '服务已停止', '服务当前未运行，请启动服务以开始使用');
				}, 2000);
			} else {
				addOutput(`停止失败: ${data.error}`, 'error');
				updateServiceStatus('online', '服务停止失败', data.error);
			}
		})
		.catch(error => {
			addOutput(`请求失败: ${error}`, 'error');
		});
}

// 编译并启动服务
function compileAndStart() {
	updateServiceStatus('starting', '编译中...', '正在编译项目，请稍候...');
	addOutput('开始编译 Lunar Astral Agents...', 'info');

	fetch('/control_panel/compile', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
		},
		body: JSON.stringify(getFormData())
	})
		.then(response => response.json())
		.then(data => {
			if (data.success) {
				addOutput('编译成功', 'success');
				addOutput(data.message, 'info');

				// 编译成功后自动启动服务
				addOutput('编译完成，正在启动服务...', 'info');
				startService();
			} else {
				addOutput(`编译失败: ${data.error}`, 'error');
				updateServiceStatus('offline', '编译失败', data.error);
			}
		})
		.catch(error => {
			addOutput(`编译请求失败: ${error}`, 'error');
			updateServiceStatus('offline', '编译失败', error);
		});
}

// 更新服务状态显示
function updateServiceStatus(status, text, details) {
	const statusElement = document.getElementById('serviceStatus');
	const indicator = document.getElementById('statusIndicator');
	const statusText = document.getElementById('statusText');
	const statusDetails = document.getElementById('statusDetails');

	// 移除所有状态类
	statusElement.classList.remove('online', 'offline', 'starting');
	indicator.classList.remove('status-online', 'status-offline', 'status-starting');

	// 添加新状态类
	statusElement.classList.add(status);
	indicator.classList.add(`status-${status}`);

	// 更新文本
	statusText.textContent = text;
	statusDetails.textContent = details;
}

// 保存配置
function saveConfig() {
	const config = getFormData();
	localStorage.setItem('lunarAstralConfig', JSON.stringify(config));
	addOutput('配置已保存到本地存储', 'success');
}

// 加载配置
function loadConfig() {
	const savedConfig = localStorage.getItem('lunarAstralConfig');
	if (savedConfig) {
		const config = JSON.parse(savedConfig);

		// 应用保存的配置到表单
		document.getElementById('system_url_port').value = config.system_url_port || 36789;
		document.getElementById('system_dev_mode').checked = config.system_dev_mode || false;
		document.getElementById('use_local_network').checked = config.use_local_network || false;
		document.getElementById('port_release').checked = config.port_release || false;
		document.getElementById('model_system_port').value = config.model_system_port || 0;
		document.getElementById('model_url_port').value = config.model_url_port || 40318;
		document.getElementById('model_file_path').value = config.model_file_path || './local_data/models';
		document.getElementById('model_embedding_index').value = config.model_embedding_index || 'void';
		document.getElementById('model_reasoning_index').value = config.model_reasoning_index || 'void';
		document.getElementById('model_visualing_index').value = config.model_visualing_index || 'void';
		document.getElementById('out').value = config.out || '';
		document.getElementById('size').value = config.size || 2048;
		document.getElementById('compression').value = config.compression || 5;
		document.getElementById('level').value = config.level || 3;

		addOutput('已加载保存的配置', 'success');
	}
}

// 页面加载时初始化
window.addEventListener('load', () => {
	addOutput('控制面板初始化完成', 'success');
	addOutput('等待用户操作...', 'info');
	loadConfig();
});
